package com.taomu.app.zongchouhuli.http.api;


import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * Created by pxy on 2018/4/24.
 */

public class RequestUpload extends BaseRequest {

    private static RequestUpload _instance;

    private RequestUpload(){

    }


    public static RequestUpload getIntence(){
        if (_instance == null) {                // Single Checked
            synchronized (Request.class) {
                if (_instance == null) {        // Double checked
                    _instance = new RequestUpload();
                }
            }
        }
        return _instance;
    }

    /**
     * 上传文件
     * @return
     */
    public Observable<String> uploadFile(List<File> imgsfiles) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        for (File file : imgsfiles) {
            // TODO: 16-4-2  这里为了简单起见，没有判断file的类型
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
            builder.addFormDataPart("file", file.getName(), requestBody);
        }
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return NetWork.getUploadApiService().getUploadPostResponse(getToken(), "home/base/upload_one", multipartBody)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        return responseBody.string();
                    }
                });
    }

    public Observable<String> uploadSingleFile(File imgsfiles) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
            // TODO: 16-4-2  这里为了简单起见，没有判断file的类型
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imgsfiles);
        MultipartBody.Part part = MultipartBody.Part.createFormData("image", imgsfiles.getName(), requestBody);
        return NetWork.getUploadApiService().getUploadSinglePostResponse(getToken(), "home/base/upload_one", part)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        return responseBody.string();
                    }
                });
    }
}
